let selprovince = document.getElementById('selprovince');
let selcity = document.getElementById('celcity');

let SPprovince = document.getElementById('SPprovince');
let SPcity = document.getElementById('SPcity');

const BASE_URL = 'https://api.huhuiyu.top';

// 通过ajax请求获取省份数据
function queryprovince() {
  let promise = axios({
    url: BASE_URL + '/link/provinces',
    method: 'get',
    data: '',
  });

  promise
    .then((resp) => {
      console.log('服务器返回的数据', resp.data);
      let info = resp.data;
      if (!info.success) {
        alert(info.message);
        return;
      }
      // 成功获取数据就填写在select中
      selprovince.innerHTML = '';
      for (let i = 0; i < info.data.length; i++) {
        let pro = info.data[i];
        console.log('省份：', pro);

        // 创建option元素

        let op = document.createElement('option');
        op.append(pro.province);
        op.setAttribute('value', pro.pid);
        // 添加到省份的select中
        selprovince.append(op);
      }

      // 设置省份的默认值
      selprovince.selectedIndex = 17;
      querycity();
    })
    .catch((err) => {
      console.error(err);
    });
}
// 联动查询城市信息
function querycity() {
  // 显示选中的省份编号
  SPprovince.innerHTML = selprovince.value;
  // 通过ajax查询省份对应的城市
  let promise = axios({
    url: `${BASE_URL}/link/cities/${selprovince.value}`,
    method: 'get',
    data: '',
  });
  promise
    .then((resp) => {
      let info = resp.data;
      if (!info.success) {
        alert(info.message);
        return;
      }
      selcity.innerHTML = '';
      for (let i = 0; i < info.data.length; i++) {
        let city = info.data[i];
        let op = document.createElement('option');
        op.append(city.city);
        op.setAttribute('value', city.cid);
        selcity.append(op);
      }
      selcity.selectedIndex = 0;
      SPcity.innerHTML = selcity.value;


    })
    .catch((err) => {
      console.error(err);
    });
}

selprovince.addEventListener('change', () => {
  querycity();
});

queryprovince();



selcity.addEventListener('change', () => {
  SPcity.innerHTML = selcity.value;
});
// 按照上课的联动效果完成部门员工的联动查询
